package com.im.chen.unionpay;

import android.content.ContentResolver;
import android.content.Context;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;
import android.text.TextUtils;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SmsObserver extends ContentObserver {

    private static final String TAG="SmsObserver";

    private static final String SMS_URI_INBOX = "content://sms/inbox";
    private OnReceive mOnReceive=null;
    private Context mContext;
    private String mSmsContent;
    private JSONObject mConfig=null;
    /**
     * Creates a content observer.
     *
     * @param handler The handler to run {@link #onChange} on, or null if none.
     */
    public SmsObserver(Handler handler, Context context, JSONObject config, OnReceive onReceive) {
        super(handler);
        this.mOnReceive=onReceive;
        this.mContext=context;
        this.mConfig=config;
    }

    @Override
    public void onChange(boolean selfChange) {
        super.onChange(selfChange);
        String regx="\\d{6}";
        Cursor cursor=null;

        ContentResolver contentResolver=mContext.getContentResolver();
        String selection=" read = ? and body like ?  ";
        String keyword="验证码";
        int read=0;
        String[] selectionArgs=new String[]{"0","%验证码%"};
        try {
            //自定义参数，精确获取
            if (mConfig!=null){
                String tmpRegx=mConfig.optString("regx",null);
                String tmpAddress=mConfig.optString("address",null);
                String tmpKeyWord=mConfig.optString("keyword",null);
//                codeSum=mConfig.optInt("codeSize",6);
                if (tmpRegx!=null){
                    regx=tmpRegx;
                }
                if (tmpAddress!=null){
                    //号码有可能带（）或这空格要去掉才能匹配
                    tmpAddress=tmpAddress
                            .replaceAll("\\s*","")
                            .replace("(","")
                            .replace(")","")
                            .replace("-","");
                    selection+=" and address = ?";
                    keyword=tmpKeyWord==null?keyword:tmpKeyWord;
                    selectionArgs =new String[]{"0","%"+keyword+"%",tmpAddress};//
                }
            }
            LogUtil.d(TAG,"onChange ");
            cursor=contentResolver.query(Uri.parse(SMS_URI_INBOX),new String[]{"_id","address","body","read"},
                    selection,selectionArgs,"date desc");

            if (cursor!=null){
                cursor.moveToFirst();
                if (cursor.moveToFirst()){
                    String smsBody=cursor.getString(cursor.getColumnIndex("body"));
                    String smsAddress=cursor.getString(cursor.getColumnIndex("address"));
                    LogUtil.d(TAG,"address: "+smsAddress+" smsbody: "+smsBody);
//                    String regEx = "\\d{6}";
                    mSmsContent=matchContent(smsBody,regx);
                    if (!TextUtils.isEmpty(mSmsContent)) {
                        mOnReceive.onSuccess(mSmsContent);
                    }else{
                        mOnReceive.onFailed(mSmsContent);
                    }
                }else{
                    LogUtil.d(TAG,"not move to first!");
                }
            }
        }catch (Exception ex){
            LogUtil.e(TAG,ex);
        }

    }

    private String matchContent(String content,String regx){
        Pattern p = Pattern.compile(regx);
        Matcher m = p.matcher(content);
        Map<Integer,String> codeMap=new HashMap<>();
        //有可能的都匹配了
        while (m.find()){
            codeMap.put(m.start(),m.group());
        }
        int codeSize=codeMap.size();
        if (codeSize==1){
            //精确匹配
            for (int key:codeMap.keySet()
                    ) {
                mSmsContent=codeMap.get(key);
            }
        }else if (codeSize>=2){
            //匹配了多个，需要赛选
            int index=0;
            String checkStr;
            for (int key:codeMap.keySet()
                    ) {
                checkStr=content.substring(index,key);
                if (checkStr.contains(content)){
                    mSmsContent=codeMap.get(key);
                    break;
                }else if (checkStr.contains("验证")){
                    mSmsContent=codeMap.get(key);
                    break;
                }
                index=key;
            }
        }else{
            //匹配失败
            mSmsContent=null;
        }
        return mSmsContent;
    }

    interface OnReceive{
        void onFailed(String result);
        void onSuccess(String result);
    }
}
